/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import jpa.exceptions.NonexistentEntityException;
import model.Obat;
import model.ObatQuery;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

  /**
   *
   * @author atikahSH
   *
   */
public class ObatManagement extends HttpServlet {

    private static final String TMP_DIR_PATH = "c:/tmp";
    private File tmpDir;
    private static final String DESTINATION_DIR_PATH = "pictures";
    private File destinationDir;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        tmpDir = new File(TMP_DIR_PATH);
        String realPath = getServletContext().getRealPath(DESTINATION_DIR_PATH);
        destinationDir = new File(realPath);
    }

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, NonexistentEntityException, ParseException {
        String page = request.getParameter("page"); //variabel bantu untuk melakukan mapping halaman
        RequestDispatcher dis = null;
        HttpSession session = request.getSession();
        Obat obat = new Obat();
        ObatQuery eq = new ObatQuery();
        DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
        fileItemFactory.setRepository(tmpDir);
        ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
        /* pada semua percabangan di bawah ini, akan dilakukan pemanggilan fungsi dari kelas
         * AccountLogic atau langsung redirect ke halaman jsp sesuai dengan parameter dari page
         * yang dituliskan pada address bar web browser dengan kondisi nilai page tidak sama dengan null
         */
        if (page != null) {
            /* memanggil fungsi untuk menambahakan Obat
             */
            if (page.equals("added")) {
                session.removeAttribute("error");
                ObatManagementLogic eml = new ObatManagementLogic(request);
                dis = request.getRequestDispatcher(eml.tambahObat());
            }/* redirect ke halaman tambahObat
             */ else if (page.equals("add")) {
                session.removeAttribute("error");
                session.removeAttribute("tempAddObat");
                dis = request.getRequestDispatcher("tambahObat.jsp");
            }/* memanggil fungsi untuk menampilkan daftar Obat dan menghapus obat
             */ else if (page.equals("list")) {
                session.removeAttribute("error");
                ObatManagementLogic eml = new ObatManagementLogic(request);
                dis = request.getRequestDispatcher(eml.hapusObat());
            } /* memanggil fungsi untuk menampilkan Detail Obat
             */ else if (page.equals("show")) {
                session.removeAttribute("error");
                ObatManagementLogic eml = new ObatManagementLogic(request);
                dis = request.getRequestDispatcher(eml.lihatObat());
            } /* memanggil fungsi untuk menampilkan Halaman Pencarian Obat
             */ else if (page.equals("search")) {
                session.removeAttribute("error");
                dis = request.getRequestDispatcher("cariObat.jsp");
            }/* memanggil fungsi untuk menampilkan Hasil Pencarian Obat
             */ else if (page.equals("searched")) {
                session.removeAttribute("error");
                ObatManagementLogic eml = new ObatManagementLogic(request);
                dis = request.getRequestDispatcher(eml.searchObats());
            } /* memanggil fungsi untuk mengubah Obat
             */ else if (page.equals("edit")) {
                session.removeAttribute("error");
                ObatManagementLogic eml = new ObatManagementLogic(request);
                dis = request.getRequestDispatcher(eml.ubahObat());
            }/* memanggil fungsi untuk menyimpan Obat yang telah dirubah
             */ else if (page.equals("edited")) {
                session.removeAttribute("error");
                ObatManagementLogic eml = new ObatManagementLogic(request);
                dis = request.getRequestDispatcher(eml.simpanUbahObat());
            }/* redirect ke halaman upload
             */ else if (page.equals("upload")) {
                session.removeAttribute("error");
                dis = request.getRequestDispatcher("gambarObat.jsp");
            }/* memanggil fungsi untuk melakukan upload gambar
             */ else if (page.equals("uploaded")) {
                session.removeAttribute("error");
                try {
                    List items = uploadHandler.parseRequest(request);
                    Iterator itr = items.iterator();
                    /* melakukan eksekusi proses upload
                     */ while (itr.hasNext()) {
                        FileItem item = (FileItem) itr.next();
                        File file = new File(destinationDir, item.getName());
                        if (file.getName().substring(file.getName().length() - 3, file.getName().length()).equals("jpg")
                                || file.getName().substring(file.getName().length() - 3, file.getName().length()).equals("JPG")
                                || file.getName().substring(file.getName().length() - 3, file.getName().length()).equals("jpeg")
                                || file.getName().substring(file.getName().length() - 3, file.getName().length()).equals("JPEG")) {
                            item.write(file);
                            String gambar = DESTINATION_DIR_PATH + "/" + file.getName();
                            /* menenetukan nama tempat penyimpanan file upload pada database
                             */
                            if (session.getAttribute("uname") != null) {
                                obat = (Obat) session.getAttribute("ename");
                                obat.setGambar(gambar);
                                session.setAttribute("ename", obat);
                                eq.editObat(obat);
                                session.removeAttribute("tempEditObat");
                                dis = request.getRequestDispatcher("lihatObat.jsp");
                            } else {
                                session.setAttribute("error", "sudah logout sebelumnya");
                                dis = request.getRequestDispatcher("index.jsp");
                            }

                        } else {
                            session.setAttribute("error", "format gambar harus .jpg atau .JPG");
                            dis = request.getRequestDispatcher("gambarObat.jsp");
                        }
                    }
                } catch (FileUploadException ex) {
                    log("Error encountered while parsing the request", ex);
                } catch (Exception ex) {
                    log("Error encountered while uploading file", ex);
                }
            }
        } /* ketika page bernilai null maka akan dipanggil fungsi untuk redirect ke home
         */ else {
            session.removeAttribute("error");
            AccountLogic al = new AccountLogic(request);
            dis = request.getRequestDispatcher(al.home());
        }
        dis.forward(request, response);
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            try {
                processRequest(request, response);
            } catch (ParseException ex) {
                Logger.getLogger(ObatManagement.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (NonexistentEntityException ex) {
            Logger.getLogger(ObatManagement.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            try {
                processRequest(request, response);
            } catch (ParseException ex) {
                Logger.getLogger(ObatManagement.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (NonexistentEntityException ex) {
            Logger.getLogger(ObatManagement.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
